package com.app.trafficclient.WoDeZuoJia;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.app.trafficclient.R;
import com.app.trafficclient.util.GetUrl;
import com.app.trafficclient.util.MyLoadDialog;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import static android.content.ContentValues.TAG;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragmentWoDeYuE.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragmentWoDeYuE#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentWoDeYuE extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public FragmentWoDeYuE() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragmentWoDeYuE.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentWoDeYuE newInstance(String param1, String param2) {
        FragmentWoDeYuE fragment = new FragmentWoDeYuE();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    RelativeLayout fragYuERelaYanSe1;
    TextView fragYuETvZhuangTAi1;
    TextView fragYuETvYuE1;
    RelativeLayout fragYuERelaYanSe2;
    TextView fragYuETvZhuangTAi2;
    TextView fragYuETvYuE2;
    RelativeLayout fragYuERelaYanSe3;
    TextView fragYuETvZhuangTAi3;
    TextView fragYuETvYuE3;
    RelativeLayout fragYuERelaYanSe4;
    TextView fragYuETvZhuangTAi4;
    TextView fragYuETvYuE4;
     static  RequestQueue requestQueue;
     static TextView[] textViews = new TextView[5];
     RelativeLayout[] relativeLayouts = new RelativeLayout[5];
    MyDialogChongZhi myDialogChongZhi;
    Handler handler;
    Handler handler1;
    MyLoadDialog myLoadDialog;
    boolean flag = true;
    boolean isOK = false;
    SharedPreferences sharedPreferences;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View convertView = inflater.inflate(R.layout.fragment_yu_e, container, false);
        fragYuERelaYanSe1 = convertView.findViewById(R.id.fragYuE_Rela_yanSe1);
       fragYuETvZhuangTAi1 = convertView.findViewById(R.id.fragYuE_tv_zhuangTAi1);
        fragYuETvYuE1 = convertView.findViewById(R.id.fragYuE_tv_yuE1);
      fragYuERelaYanSe2 = convertView.findViewById(R.id.fragYuE_Rela_yanSe2);
      fragYuETvZhuangTAi2 = convertView.findViewById(R.id.fragYuE_tv_zhuangTAi2);
       fragYuETvYuE2 = convertView.findViewById(R.id.fragYuE_tv_yuE2);
       fragYuERelaYanSe3 = convertView.findViewById(R.id.fragYuE_Rela_yanSe3);
       fragYuETvZhuangTAi3 = convertView.findViewById(R.id.fragYuE_tv_zhuangTAi3);
        fragYuETvYuE3 = convertView.findViewById(R.id.fragYuE_tv_yuE3);
        fragYuERelaYanSe4 = convertView.findViewById(R.id.fragYuE_Rela_yanSe4);
        fragYuETvZhuangTAi4 = convertView.findViewById(R.id.fragYuE_tv_zhuangTAi4);
       fragYuETvYuE4 = convertView.findViewById(R.id.fragYuE_tv_yuE4);
        return convertView;
    }

    @Override
    public void onStart() {
        super.onStart();
        requestQueue = Volley.newRequestQueue(getContext());
        sharedPreferences = this.getActivity().getSharedPreferences("yueyuzhi",Context.MODE_PRIVATE);
        textViews[1] =fragYuETvYuE1;
        textViews[2] = fragYuETvYuE2;
        textViews[3] = fragYuETvYuE3;
        textViews[4] = fragYuETvYuE4;
        relativeLayouts[1] = fragYuERelaYanSe1;
        relativeLayouts[2] = fragYuERelaYanSe2;
        relativeLayouts[3] = fragYuERelaYanSe3;
        relativeLayouts[4] = fragYuERelaYanSe4;
        initTimer();

        initListener();
    }

    private void initTimer() {
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                sendPost(msg.what);
                Log.d("flagTF请求", "ok ");
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {

                while (flag){
                    handler.sendEmptyMessage(1);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag){
                    handler.sendEmptyMessage(2);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag){
                    handler.sendEmptyMessage(3);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag){
                    handler.sendEmptyMessage(4);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void initListener() {
        for (int i=1;i<=4;i++){
            textViews[i].setOnClickListener(this);
        }
        myLoadDialog = new MyLoadDialog(getContext());
        MyLoadDialog.showDia();
    }

    private  void sendPost(int i) {
        Log.d("falgTF",sharedPreferences.getBoolean("flag",false)+"");

            String url = GetUrl.getUrl() +"action/GetCarAccountBalance.do";
            Map<String, Object> map = new HashMap<>();
            map.put("CarId",i);
            map.put("UserName","user1");
            JSONObject jsonObject = new JSONObject(map);
            final int finalI = i;
            JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST,url,jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    String string = jsonObject.toString();
                    Gson gson = new Gson();
                    BeanYuE beanYuE = gson.fromJson(string, BeanYuE.class);
                    textViews[finalI].setText(String.valueOf(beanYuE.getBalance()));
//                    Log.d("tag余额", "onResponse: ok"+string);
                    newTimer1();
                    MyLoadDialog.disDia();

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(getContext(), finalI +"号小车余额获取失败，正在重试！",Toast.LENGTH_LONG).show();
                    MyLoadDialog.disDia();
                }
            });
            jsonRequest.setTag("tag");
            requestQueue.add(jsonRequest);
    }//sendPost

    private void newTimer1() {

            handler1 = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    duibi();
                    Log.d("flagTF对比","对比执行了");
                }
            };
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (flag) {
                        handler1.sendEmptyMessage(1);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }

    private  void duibi() {
        int money;
//        Log.d("falgTF",sharedPreferences.getBoolean("flag",false)+"");

         if (sharedPreferences.getBoolean("flag",false)){
//             Log.d("falgTF",sharedPreferences.getBoolean("flag",false)+"");
              money = Integer.parseInt(sharedPreferences.getString("money","0"));
              for (int i =1;i<=4;i++){
                  if (Integer.parseInt(textViews[i].getText().toString()) <= money){
                      relativeLayouts[i].setBackgroundColor(getResources().getColor(R.color.zhongdu)); //对应的控件  红色
                  }else{
                      relativeLayouts[i].setBackgroundColor(getResources().getColor(R.color.changtong));
                  }
              }
         }
    }
    @Override
    public void onDestroy() {
        requestQueue.cancelAll("tag");
        flag =false;
        super.onDestroy();
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fragYuE_tv_yuE1: showDialog(1);break;
            case R.id.fragYuE_tv_yuE2: showDialog(2);break;
            case R.id.fragYuE_tv_yuE3: showDialog(3);break;
            case R.id.fragYuE_tv_yuE4: showDialog(4);break;
        }
    }

    private void showDialog(int i) {
        myDialogChongZhi = new MyDialogChongZhi(getContext(),i);
        myDialogChongZhi.setCanceledOnTouchOutside(false);
        myDialogChongZhi.show();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
